from django.shortcuts import render, redirect
from django.http import HttpResponse
from ..models import Department, UserInfo, PrettyNum, Admin
from django import forms
from django.forms import Form, ModelForm
from django.utils.safestring import mark_safe
from .pagination import Pagination
from .bootstrap import BootStrapModelForm
from django.core.validators import RegexValidator
from django.core.exceptions import ValidationError
from ..utils.encrypt import md5

class UserModelForm(BootStrapModelForm):

    # 需求：进行更多的表单数据校验---重写forms
    name = forms.CharField(min_length=2, label="用户名") # 字符数至少是2
    # password = forms.CharField(validators='[\d\w_]+',label="密码")  # validators里写正则表达式校验

    class Meta:
        model = UserInfo
        fields = ['name', 'password', 'age', 'create_time', 'salary', 'gender', 'depart']
        """  手动添加widgets，给每个字段添加css属性
        widgets = {
            "name": forms.TextInput(attrs={"class": "form-control"}),
        }  
        """

class PrettynumModelForm(BootStrapModelForm):
    # 校验字段方式1
    mobile = forms.CharField(
        label="手机号",
        validators=[RegexValidator(r'^1[345][0-9]+$', '数字必须以13,14,15开头')],
    )
    class Meta:
        model = PrettyNum
        # fields = ['mobile', 'price', 'level', 'status']
        fields = "__all__"  # 这个表示所有的字段
        # exclude = ['level']  # 排除那些字段

    # 检验字段方式2（钩子）
    def clean_price(self):
        txt_price = self.cleaned_data["price"]  # 获取用户传入的price
        if txt_price < 100 or txt_price > 1000:
            raise ValidationError("价格在100-1000之间")
        return txt_price
    # 校验手机号是否已存在
    def clean_mobile(self):
        txt_mobile = self.cleaned_data["mobile"]
        isExists = PrettyNum.objects.filter(mobile=txt_mobile).exists()
        if isExists:
            raise ValidationError("手机号已存在，不允许重复")
        return txt_mobile

class PrettynumEditModelForm(forms.ModelForm):
    # mobile = forms.CharField(disabled=True, label="手机号")
    mobile = forms.CharField(
        label="手机号",
        validators=[RegexValidator(r'^1[345][0-9]+$', '数字必须以13,14,15开头')],
    )
    class Meta:
        model = PrettyNum
        fields = ['mobile', 'price', 'level', 'status']
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for name, field in self.fields.items():
            field.widget.attrs = {'class': 'form-control', 'placeholder': field.label}
    def clean_price(self):
        txt_price = self.cleaned_data["price"]
        if txt_price < 100 or txt_price > 1000:
            raise ValidationError("价格在100-1000之间")
        return txt_price
    def clean_mobile(self):
        txt_mobile = self.cleaned_data["mobile"]
        # self.instance.pk     # 当前编辑行的主键
        isExists = PrettyNum.objects.exclude(id=self.instance.pk).filter(mobile=txt_mobile).exists()
        if isExists:
            raise ValidationError("手机号已存在，不允许重复")
        return txt_mobile


class AdminModelForm(forms.ModelForm):
    confirm_password = forms.CharField(label='确认密码', widget=forms.PasswordInput)
    class Meta:
        model = Admin
        fields = ['username', 'password', 'confirm_password']
        widgets = {
            'password': forms.PasswordInput(render_value=True)
        }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for name, field in self.fields.items():
            field.widget.attrs = {'class': 'form-control', 'placeholder': field.label}

    def clean_confirm_password(self):
        pwd = self.cleaned_data.get('password')
        confirm = md5(self.cleaned_data.get('confirm_password'))
        if confirm != pwd:
            raise ValidationError('密码不一致')
        return confirm  # 这里的返回值作为数据库保存的该字段值

    def clean_password(self):
        pwd = self.cleaned_data.get('password')
        return md5(pwd)

class AdminEditModelForm(BootStrapModelForm):
    class Meta:
        model = Admin
        fields = ['username']

class AdminResetModelForm(forms.ModelForm):
    username = forms.CharField(label='管理员名称', disabled=True)
    confirm_password = forms.CharField(label='确认密码', widget=forms.PasswordInput)
    class Meta:
        model = Admin
        fields = ['username', 'password', 'confirm_password']
        widgets = {
            'password': forms.PasswordInput(render_value=True)
        }
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for name, field in self.fields.items():
            field.widget.attrs = {'class': 'form-control', 'placeholder': field.label}

    def clean_password(self):
        pwd = self.cleaned_data.get('password')
        md5_pwd = md5(pwd)
        exists = Admin.objects.filter(id=self.instance.pk, password=md5_pwd).exists()
        if exists:
            raise ValidationError('密码不能与之前的一致')
        return md5_pwd

    def clean_confirm_password(self):
        pwd = self.cleaned_data.get('password')
        confirm = self.cleaned_data.get('confirm_password')
        if md5(confirm) != pwd:
            raise ValidationError('密码不一致')
        return confirm